use std::error::Error;

use player::{logger, media_player::MediaPlayer};

fn main() -> Result<(), Box<dyn Error>> {
    println!("Hello, world!");
    logger::init_logger()?;

    let file_path = "/home/shc_fighter/data/忍者神龟:变种时代.HD1280超清中英双字.mp4";
    let file_path = "/home/shc_fighter/data/workspace/rust/rust-player/res/test11.mp4";
    let file_path = "/home/shc_fighter/Movies/忍者神龟：变种时代.BD1280超清国英双语中英双字.mp4";
    //let file_path = "/home/shc_fighter/Movies/泰坦尼克号_1080p.mp4";
    //let file_path = "/home/shc_fighter/Downloads/2.netty服务端入门补充~1.avi";
    //let file_path = "/home/shc_fighter/Downloads/15.使用CXF为普通BBS应用增加WebService功能.wmv";
    //let file_path = "/home/shc_fighter/data/Music/";

    let (mut media_player, video, audio) = MediaPlayer::new(file_path)
        .avformat_alloc_context()?
        .avformat_open_input()?
        .avformat_find_stream_info()?
        .av_dump_format()?
        .nb_streams()?;

    
    let mut audio_player = None;
    if let Some(player) = audio {
        audio_player = Some(player
            .avcodec_alloc_context()?
            .avcodec_parameters_to_context()?
            .avcodec_find_decoder()?
            .avcodec_open()?
            .swr_context()?
            .get_samples_buffer_size()?
            .init_audio_sdl()?
            .decode_packet()?
            .player()?);
    }

    let mut video_player = None;
    if let Some(player) = video {
        video_player = Some(player
            .avcodec_alloc_context()?
            .avcodec_parameters_to_context()?
            .avcodec_find_decoder()?
            .avcodec_open()?
            .init_window()?
            .decode_packet()?
            .player()?);
    }
    
    media_player = media_player.read_packet()?
        .seek()?;

    if let Some(audio_player) = audio_player {
        audio_player.close()?;
    }
    
    if let Some(video_player) = video_player {
        video_player.close()?;
    }

    media_player.close()?;

    Ok(())
}
